package systems;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.google.gson.Gson;

import entities.Recently;

public class RecentlyArticle {
	
	private static String cacheName = "recentlyArticle";
	
	private static int limit = 500;
	
	private static List<String> ids = new ArrayList<String>();
	
	public static void insert(String name, String url) {
		Cache cache=null;
    	try {
		    cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		} catch (CacheException e1) {
		   e1.printStackTrace();
		}
		
		Recently recently = new Recently();
		recently.setName(name);
		recently.setUrl(url);
		
		String json = new Gson().toJson(recently);
		
		if (ids.contains(json)) {
			ids.remove(json);
		}
		
		if (ids.size() >= limit) {
			ids.remove(limit - 1);
		}
		
		ids.add(0, json);
		
		cache.put(cacheName, ids);
	}
	
	public static List<String> getArticles() {
		
		return ids;
	}
}
